package com.zhoutao.blog.seven.service.impl;

import com.zhoutao.blog.seven.dao.repository.TagRelationRepository;
import com.zhoutao.blog.seven.dao.repository.TagRepository;
import com.zhoutao.blog.seven.model.converter.TagConverter;
import com.zhoutao.blog.seven.model.detail.TagDetail;
import com.zhoutao.blog.seven.model.response.Tag;
import com.zhoutao.blog.seven.service.TagService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class TagServiceImpl implements TagService {

    private final TagRepository tagRepository;

    private final TagConverter tagConverter;

    private final TagRelationRepository tagRelationRepository;

    @Override
    public List<TagDetail> list() {
        List<Tag> tags = tagRepository.list().stream().map(tagConverter::converterFrom).collect(Collectors.toList());
        // 查询对应Tag的文章数量
        if (CollectionUtils.isEmpty(tags)) {
            return Collections.emptyList();
        }
        List<Long> tagIds = tags.stream().map(Tag::getId).collect(Collectors.toList());
        Map<Long, Long> articleCountMap = tagRelationRepository.groupByTagId(tagIds);
        return tags.stream().map(tag -> {
            Long count = articleCountMap.getOrDefault(tag.getId(), 0L);
            if (count == null || count == 0) {
                return null;
            }
            return new TagDetail(tag, count);
        }).filter(Objects::nonNull).collect(Collectors.toList());
    }
}
